package com.ikangtai.shecare.stickycalendar.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.stickycalendar.abs.RefreshListener;
import com.ikangtai.shecare.stickycalendar.adapter.ListItemAdapter;
import com.ikangtai.shecare.stickycalendar.adapter.MonthCalendarAdpter;
import com.ikangtai.shecare.stickycalendar.adapter.PhyListAdapter;
import com.ikangtai.shecare.stickycalendar.adapter.WeekCalendarAdapter;
import com.ikangtai.shecare.stickycalendar.bean.ListBean;
import com.ikangtai.shecare.stickycalendar.bean.MoreDayState;
import com.ikangtai.shecare.stickycalendar.fragment.widget.HandMoveLayout;
import com.ikangtai.shecare.stickycalendar.fragment.widget.HasTwoAdapterViewpager;
import com.ikangtai.shecare.stickycalendar.http.util.MensesMsg;
import com.ikangtai.shecare.stickycalendar.utils.DateUtils;
import com.jaeger.library.StatusBarUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 我的日程
 */
public class CalendarRecordFragment extends Fragment implements RefreshListener, TopBar.OnTopBarClickListener {

    private ListItemAdapter listItemAdapter;
    private List<ListBean> listBeens;
    private Map<String, MoreDayState> dayStates;
    private List<UserRecordData> userRecordDatas;
    private List<String> list = new ArrayList<>();

    public CalendarRecordFragment() {
        super();
    }

    private TopBar topBar;
    private View view;
    private ListView listView;
    private HandMoveLayout handMoveLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        EventBus.getDefault().register(this);

        view = inflater.inflate(R.layout.fragment_my_calender, container, false);
        listView = (ListView) view.findViewById(R.id.list);
        topBar = (TopBar) view.findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(this);
        return view;


    }


    @Override
    public void leftClick() {

    }

    @Override
    public void midLeftClick() {

    }

    @Override
    public void midRightClick() {

    }

    @Override
    public void rightClick() {


        Toast.makeText(getActivity(), "aaaaa", Toast.LENGTH_SHORT).show();
//        initCalendarDate();
        dayStates.clear();
//        adpter.notifyDataSetChanged();
//        weekCalendarAdpter.notifyDataSetChanged();

        viewPager.setCurrentItem(1200);
        adpter.notifyDataSetChanged();
        viewpagerWeek.setCurrentItem(4800);
        weekCalendarAdpter.notifyDataSetChanged();
    }

    private void init() {
        listBeens = new ArrayList<>();
        dayStates = new HashMap<>();
        userRecordDatas = new ArrayList<>();
        list.add("1");
        initCalendarDate();
        initData();
        PhyListAdapter phyListAdapter = new PhyListAdapter(getActivity(), list);
        listItemAdapter = new ListItemAdapter(getActivity(), listBeens, phyListAdapter);

        listView.setAdapter(listItemAdapter);
    }

    public Map<String, MoreDayState> getDayStates() {

        userRecordDatas = UserRecordData.getUserRecordDataList(getActivity(), App.userName, App.dayUnitDSOutputsList.get(0).date, App.dayUnitDSOutputsList.get(App.dayUnitDSOutputsList.size() - 1).date);

        for (int i = 0; i < App.dayUnitDSOutputsList.size(); i++) {
            dayStates.put(DateUtil.getDateStr2bit(App.dayUnitDSOutputsList.get(i).date),
                    new MoreDayState(App.dayUnitDSOutputsList.get(i).getPeriod(App.status),
                            userRecordDatas.get(i).isCopulationHaveSex(),
                            getNormalBg(i), getSelectBg(i),
                            getNormalTextColor(i),
                            getSelectorColor()));
        }
        return dayStates;
    }

    private int getNormalBg(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status)) {
            case "yjq":
                if (App.dayUnitDSOutputsList.get(i) == null || App.dayUnitDSOutputsList.get(i).toString().length() <= 0) {
                    return R.drawable.re_circle_bg_pink_pre;
                } else {
                    if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                        return R.drawable.re_circle_bg_pink;
                    } else {
                        return R.drawable.re_circle_bg_pink_pre;
                    }
                }
            default:
                return R.drawable.circle_bg_white;
        }
    }

    private int getSelectBg(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status)) {
            case "yjq":
                if (App.dayUnitDSOutputsList.get(i) == null || App.dayUnitDSOutputsList.get(i).toString().length() <= 0) {
                    return R.drawable.re_circle_bg_pink_pre;
                } else {
                    if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                        return R.drawable.re_circle_bg_pink;
                    } else {
                        return R.drawable.re_circle_bg_pink_pre;
                    }
                }
            case "lpq":
                return R.drawable.re_circle_bg_blue;
            case "htq":
                return R.drawable.re_circle_bg_blue;
            case "aqq":
                return R.drawable.re_circle_bg_blue;
            case "wxq":
                return R.drawable.re_circle_bg_green;
            case "plq":
                return R.drawable.re_circle_bg_green;

            default:
                if (App.dayUnitDSOutputsList.get(i).homePageOvulation == 0) {
                    return R.drawable.re_circle_bg_yellow;
                } else
                    return R.drawable.re_circle_bg_yellow;
        }


    }

    private int getNormalTextColor(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status)) {

            case "yjq":
                return R.color.white;
            case "wxq":
                return R.color.ca_green;
            case "plq":
                return R.color.ca_green;
            default:

                if (App.dayUnitDSOutputsList.get(i).homePageOvulation == 0) {
                    return R.color.ca_yellow;
                } else
                    return R.color.black;
        }
    }

    private int getSelectorColor() {
        return R.color.white;
    }

    private void initCalendarDate() {

        Observable.create(new Observable.OnSubscribe<Map<String, MoreDayState>>() {

            @Override
            public void call(Subscriber<? super Map<String, MoreDayState>> subscriber) {
                subscriber.onNext(getDayStates());
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Map<String, MoreDayState>>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {

                               }

                               @Override
                               public void onNext(Map<String, MoreDayState> strings) {

                               }
                           }

                );
    }


    private List<ListBean> initData() {
        listBeens.add(new ListBean(1));
        return listBeens;
    }


    /**
     * 调整到下个月
     */
    public void pagerNext() {
        if (viewPager != null) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);

        }
    }

    /**
     * 调整到上个月
     */
    public void pagerLast() {
        if (viewPager != null) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);

        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        handMoveLayout = (HandMoveLayout) getView().findViewById(R.id.handmovelayout);
        init();
        initCalendar();


    }

    private HasTwoAdapterViewpager viewPager;
    private HasTwoAdapterViewpager viewpagerWeek;
    private List<View> views;
    private WeekCalendarAdapter weekCalendarAdpter;

    public void initCalendar() {
        viewPager = (HasTwoAdapterViewpager) getView().findViewById(R.id.calendar_viewpager);
        viewpagerWeek = (HasTwoAdapterViewpager) getView().findViewById(R.id.calendar_viewpager_week);

        viewPager.setListener(this);
        viewpagerWeek.setListener(this);

        viewPager.setOffscreenPageLimit(0);
        viewpagerWeek.setOffscreenPageLimit(0);
        //制造月视图所需view
        views = new ArrayList<>();
        LinearLayout layout = (LinearLayout) View.inflate(getActivity(), R.layout.mouth, null);
        LinearLayout layout1 = (LinearLayout) View.inflate(getActivity(), R.layout.mouth, null);
        LinearLayout layout2 = (LinearLayout) View.inflate(getActivity(), R.layout.mouth, null);
        LinearLayout layout3 = (LinearLayout) View.inflate(getActivity(), R.layout.mouth, null);
        views.add(layout);
        views.add(layout1);
        views.add(layout2);
        views.add(layout3);


        adpter = new MonthCalendarAdpter(views, getActivity(), dayStates);
        topBar.setText(adpter.getSelectTime());
        StatusBarUtil(adpter.getSelectTime());

        adpter.setHandler(os);

        //制造日试图所需view
        List viewss = new ArrayList();
        LinearLayout layoutri = (LinearLayout) View.inflate(getActivity(), R.layout.week, null);
        LinearLayout layout1ri = (LinearLayout) View.inflate(getActivity(), R.layout.week, null);
        LinearLayout layout2ri = (LinearLayout) View.inflate(getActivity(), R.layout.week, null);
        LinearLayout layout3ri = (LinearLayout) View.inflate(getActivity(), R.layout.week, null);
        viewss.add(layoutri);
        viewss.add(layout1ri);
        viewss.add(layout2ri);
        viewss.add(layout3ri);

        weekCalendarAdpter = new WeekCalendarAdapter(viewss, getActivity(), dayStates);
        topBar.setText(adpter.getSelectTime());
        weekCalendarAdpter.setHandler(os);
        viewPager.setAdapter(adpter);
        viewPager.setCurrentItem(1200, true);
        viewpagerWeek.setAdapter(weekCalendarAdpter);
        viewpagerWeek.setCurrentItem(weekCalendarAdpter.getCount() / 2);

        //如果是周日，就翻到下一页
        Calendar today = new GregorianCalendar();
        today.setTimeInMillis(System.currentTimeMillis());
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d("position", Integer.toString(position));

            }

            @Override
            public void onPageSelected(int position) {
                Calendar today = new GregorianCalendar();
                today.setTimeInMillis(System.currentTimeMillis());
                //距离当前时间的月数(按月算)
                int month = adpter.getCount() / 2 - position;
                today.add(Calendar.MONTH, -month);
                topBar.setText(today.get(Calendar.YEAR) + "-" + (today.get(Calendar.MONTH) + 1) + "");

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewpagerWeek.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Calendar today = new GregorianCalendar();
                today.setTimeInMillis(System.currentTimeMillis());

                int day_of_week = today.get(Calendar.DAY_OF_WEEK) - 1;
                if (day_of_week == 0) {
                    day_of_week = 7;
                }
                today.add(Calendar.DATE, -day_of_week);
                //距离当前时间的周数(按周算)
                int week = weekCalendarAdpter.getCount() / 2 - position;
                today.add(Calendar.DATE, -week * 7);

                topBar.setText(today.get(Calendar.YEAR) + "-" + (today.get(Calendar.MONTH) + 1) + "");

//                setBarTitle(getTopTitleTime(today));
                //刷新本页
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private MonthCalendarAdpter adpter;
    /**
     * 用于接收上面日期改变的消息
     */
    public static final int change = 90;
    public static final int change2 = 91;

    public static final int pagerNext = 101;

    public static final int pagerLast = 102;
    public static final int selectTime = 105;

    Handler os = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 90) {
                //do same thing
            } else if (msg.what == change2) {
                handMoveLayout.setRowNum((Integer) msg.obj);
            } else if (msg.what == pagerNext) {
                pagerNext();
            } else if (msg.what == pagerLast) {
                pagerLast();
            } else if (msg.what == selectTime) {
                topBar.setText(msg.getData().getString("selectTime"));

//                topBar.setText(msg.getData().getString("selectTime"));
                StatusBarUtil(msg.getData().getString("selectTime"));
            }
        }
    };

    int currentItem = 0;

    @Override
    public void refreshListener(final ViewPager viewPager) {
//        ToastUtils.shortMsg("刷新");
        //得到这个selecttime对应的currentItem
        currentItem = 0;
        if (viewPager.getAdapter() instanceof MonthCalendarAdpter) {
            adpter.getTimeList(dayStates);
            //月视图
            currentItem = getMonthCurrentItem();
            int odl = viewPager.getCurrentItem();

            viewPager.setCurrentItem(currentItem, false);
            //刷新已经存在的3个视图view
            if (Math.abs(odl - currentItem) <= 1) {
                adpter.instantiateItem(viewPager, viewPager.getCurrentItem() - 1);

                adpter.instantiateItem(viewPager, viewPager.getCurrentItem());

                adpter.instantiateItem(viewPager, viewPager.getCurrentItem() + 1);
            }
            adpter.notifyDataSetChanged();
        } else {
            //周视图
            currentItem = getWeekCurrentItem();
            //如果是周日，就是下一周，+1
            if (DateUtils.getWeekStr(DateUtils.stringToDate(adpter.getSelectTime())).equals("星期日")) {
                currentItem++;
            }
            weekCalendarAdpter.getTimeList(dayStates);
            int odl = viewPager.getCurrentItem();
            viewPager.setCurrentItem(currentItem, false);
            //刷新已经存在的3个视图view
            if (Math.abs(odl - currentItem) <= 1) {
                weekCalendarAdpter.instantiateItem(viewPager, viewPager.getCurrentItem() - 1);

                weekCalendarAdpter.instantiateItem(viewPager, viewPager.getCurrentItem());

                weekCalendarAdpter.instantiateItem(viewPager, viewPager.getCurrentItem() + 1);
            }
            weekCalendarAdpter.notifyDataSetChanged();
        }


    }

    //得到月视图选中日期后的CurrentItem
    private int getMonthCurrentItem() {
        //此刻
        Calendar today = new GregorianCalendar();
        today.setTimeInMillis(System.currentTimeMillis());
        //选中时间
        String time = adpter.getSelectTime();
        Date date = DateUtils.stringToDate(time);
        Calendar sele = new GregorianCalendar();
        sele.setTimeInMillis(date.getTime());

        //选中时间的(MONTH)-此刻(MONTH)=月数
        int aa = sele.get(Calendar.MONTH) - today.get(Calendar.MONTH);

        return adpter.getCount() / 2 + aa;
    }

    //得到周视图选中日期后的CurrentItem
    public int getWeekCurrentItem() {
        //此刻
        Calendar today = new GregorianCalendar();
        today.setTimeInMillis(System.currentTimeMillis());
        //转为本周一
        int day_of_week = today.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0) {
            day_of_week = 7;
        }
        today.add(Calendar.DATE, -day_of_week);
        //选中时间

        String time = weekCalendarAdpter.getSelectTime();


        Date date = DateUtils.stringToDate(time);
        Calendar sele = new GregorianCalendar();
        sele.setTimeInMillis(date.getTime());

        //选中时间的(day of yeay)-此刻(day of yeay)=天数
        int aa = ((int) (sele.getTime().getTime() / 1000) - (int) (today.getTime().getTime() / 1000)) / 3600 / 24;
        int aa2 = 0;
        if (Math.abs(aa) % 7 == 0) {
            aa2 = Math.abs(aa) / 7;
        } else {
            aa2 = Math.abs(aa) / 7;
        }
        if (aa >= 0) {
            return weekCalendarAdpter.getCount() / 2 + aa2;
        } else {
            return weekCalendarAdpter.getCount() / 2 - aa2 - 1;
        }
    }

    private void StatusBarUtil(String time) {
        topBar.setBackgroundResource(getBGColor(time));
        StatusBarUtil.setColor(getActivity(), getResources().getColor(getBGColor(time)), 0);
    }

    private int getBGColor(String day) {
//        switch (Locale.getDefault().getLanguage()) {
//            case "zh":
        if (dayStates.get(day) != null) {
            switch (dayStates.get(day).getState() + "") {
                case "yjq":
                    if (App.DayUnitDSOutputMap.get(DateUtil.getStringToDate(day + " 12:00:00")) == null) {
                        return R.color.circle_bg_pink_pre;
                    } else {
                        if (App.DayUnitDSOutputMap.get(DateUtil.getStringToDate(day + " 12:00:00")).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                            return R.color.circle_bg_pink;
                        } else {
                            return R.color.circle_bg_pink_pre;
                        }
                    }
                case "lpq":
                    return R.color.circle_bg_blue;
                case "htq":
                    return R.color.circle_bg_blue;
                case "aqq":
                    return R.color.circle_bg_blue;
                case "wxq":
                    return R.color.circle_bg_red;
                case "plq":
                    return R.color.circle_bg_green;
                case "plr":
                    return R.color.circle_bg_yellow;
                default:
                    return R.color.circle_bg_blue;
            }
        } else {
            return R.color.circle_bg_blue;
        }
    }
//    }
//            default:
//                if (list.size() > 0) {
//                    switch (list.get(i).getState()) {
//                        case EnConstant.kMenstruation:
//                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
//                                return R.color.circle_bg_pink;
//                            }
//                            return R.color.circle_bg_pink_pre;
//
//                        case EnConstant.kFollicular_phase:
//                            return R.color.circle_bg_blue;
//                        case EnConstant.kLuteal:
//                            return R.color.circle_bg_yellow;
//                        case EnConstant.kSafe:
//                            return R.color.circle_bg_blue;
//                        case EnConstant.kDangerous:
//                            return R.color.circle_bg_red;
//                        default:
//                            return R.color.circle_bg_green;
//                    }
//                } else {
//                    return R.color.circle_bg_blue;
//                }
//        }

//    }

    @Subcriber
    private void refreshListener(MensesMsg mensesMsg) {

    }

}
